#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
高级搜索对话框
支持多种搜索条件的组合查询
"""

import logging
from datetime import datetime, timedelta
from typing import Dict, Any, Optional

from PyQt6.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QGridLayout, QFormLayout,
    QLabel, QLineEdit, QComboBox, QSpinBox, QDateEdit, QTimeEdit,
    QPushButton, QGroupBox, QCheckBox, QMessageBox, QFrame
)
from PyQt6.QtCore import Qt, QDate, QTime, pyqtSignal
from PyQt6.QtGui import QFont

logger = logging.getLogger(__name__)

class AdvancedSearchDialog(QDialog):
    """高级搜索对话框"""
    
    # 搜索条件信号
    search_requested = pyqtSignal(dict)
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.search_conditions = {}
        self.init_ui()
    
    def init_ui(self):
        """初始化UI"""
        self.setWindowTitle("高级搜索")
        self.setModal(True)
        self.resize(600, 500)
        
        layout = QVBoxLayout(self)
        
        # 标题
        title_label = QLabel("高级搜索条件")
        title_label.setFont(QFont("Arial", 14, QFont.Weight.Bold))
        title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(title_label)
        
        # 基本信息搜索组
        basic_group = QGroupBox("基本信息搜索")
        basic_layout = QFormLayout(basic_group)
        
        # 样本编号/ID搜索
        self.sample_number_edit = QLineEdit()
        self.sample_number_edit.setPlaceholderText("输入样本编号或ID")
        basic_layout.addRow("样本编号/ID:", self.sample_number_edit)
        
        # 患者姓名搜索
        self.patient_name_edit = QLineEdit()
        self.patient_name_edit.setPlaceholderText("输入患者姓名")
        basic_layout.addRow("患者姓名:", self.patient_name_edit)
        
        # 性别搜索
        self.gender_combo = QComboBox()
        self.gender_combo.addItems(["全部", "男", "女"])
        basic_layout.addRow("性别:", self.gender_combo)
        
        layout.addWidget(basic_group)
        
        # 年龄区间搜索组
        age_group = QGroupBox("年龄区间搜索")
        age_layout = QHBoxLayout(age_group)
        
        self.age_enable_check = QCheckBox("启用年龄搜索")
        self.age_enable_check.toggled.connect(self.toggle_age_search)
        age_layout.addWidget(self.age_enable_check)
        
        age_layout.addWidget(QLabel("年龄范围:"))
        
        self.age_min_spin = QSpinBox()
        self.age_min_spin.setRange(0, 150)
        self.age_min_spin.setValue(0)
        self.age_min_spin.setEnabled(False)
        age_layout.addWidget(self.age_min_spin)
        
        age_layout.addWidget(QLabel("至"))
        
        self.age_max_spin = QSpinBox()
        self.age_max_spin.setRange(0, 150)
        self.age_max_spin.setValue(150)
        self.age_max_spin.setEnabled(False)
        age_layout.addWidget(self.age_max_spin)
        
        age_layout.addWidget(QLabel("岁"))
        age_layout.addStretch()
        
        layout.addWidget(age_group)
        
        # 检测时间区间搜索组
        time_group = QGroupBox("检测时间区间搜索")
        time_layout = QFormLayout(time_group)
        
        self.time_enable_check = QCheckBox("启用时间搜索")
        self.time_enable_check.toggled.connect(self.toggle_time_search)
        time_layout.addRow(self.time_enable_check)
        
        # 开始时间
        start_time_layout = QHBoxLayout()
        self.start_date_edit = QDateEdit()
        self.start_date_edit.setDate(QDate.currentDate().addDays(-7))  # 默认7天前
        self.start_date_edit.setEnabled(False)
        start_time_layout.addWidget(self.start_date_edit)
        
        self.start_time_edit = QTimeEdit()
        self.start_time_edit.setTime(QTime(0, 0, 0))
        self.start_time_edit.setEnabled(False)
        start_time_layout.addWidget(self.start_time_edit)
        
        time_layout.addRow("开始时间:", start_time_layout)
        
        # 结束时间
        end_time_layout = QHBoxLayout()
        self.end_date_edit = QDateEdit()
        self.end_date_edit.setDate(QDate.currentDate())
        self.end_date_edit.setEnabled(False)
        end_time_layout.addWidget(self.end_date_edit)
        
        self.end_time_edit = QTimeEdit()
        self.end_time_edit.setTime(QTime(23, 59, 59))
        self.end_time_edit.setEnabled(False)
        end_time_layout.addWidget(self.end_time_edit)
        
        time_layout.addRow("结束时间:", end_time_layout)
        
        layout.addWidget(time_group)
        
        # 仪器信息搜索组
        instrument_group = QGroupBox("仪器信息搜索")
        instrument_layout = QFormLayout(instrument_group)
        
        # 仪器型号
        self.instrument_model_edit = QLineEdit()
        self.instrument_model_edit.setPlaceholderText("输入仪器型号")
        instrument_layout.addRow("仪器型号:", self.instrument_model_edit)
        
        # 仪器编号
        self.instrument_id_edit = QLineEdit()
        self.instrument_id_edit.setPlaceholderText("输入仪器编号")
        instrument_layout.addRow("仪器编号:", self.instrument_id_edit)
        
        # 分析模式
        self.analysis_mode_edit = QLineEdit()
        self.analysis_mode_edit.setPlaceholderText("输入分析模式")
        instrument_layout.addRow("分析模式:", self.analysis_mode_edit)
        
        # 协议类型
        self.protocol_edit = QLineEdit()
        self.protocol_edit.setPlaceholderText("输入协议类型")
        instrument_layout.addRow("协议类型:", self.protocol_edit)
        
        layout.addWidget(instrument_group)
        
        # 样本状态搜索组
        status_group = QGroupBox("样本状态搜索")
        status_layout = QFormLayout(status_group)
        
        self.status_combo = QComboBox()
        self.status_combo.addItems(["全部", "待处理", "已处理", "已发送"])
        status_layout.addRow("样本状态:", self.status_combo)
        
        layout.addWidget(status_group)
        
        # 快速时间选择
        quick_time_group = QGroupBox("快速时间选择")
        quick_time_layout = QHBoxLayout(quick_time_group)
        
        self.today_button = QPushButton("今天")
        self.today_button.clicked.connect(lambda: self.set_quick_time("today"))
        quick_time_layout.addWidget(self.today_button)
        
        self.yesterday_button = QPushButton("昨天")
        self.yesterday_button.clicked.connect(lambda: self.set_quick_time("yesterday"))
        quick_time_layout.addWidget(self.yesterday_button)
        
        self.week_button = QPushButton("最近7天")
        self.week_button.clicked.connect(lambda: self.set_quick_time("week"))
        quick_time_layout.addWidget(self.week_button)
        
        self.month_button = QPushButton("最近30天")
        self.month_button.clicked.connect(lambda: self.set_quick_time("month"))
        quick_time_layout.addWidget(self.month_button)
        
        self.clear_time_button = QPushButton("清除时间")
        self.clear_time_button.clicked.connect(self.clear_time_search)
        quick_time_layout.addWidget(self.clear_time_button)
        
        layout.addWidget(quick_time_group)
        
        # 按钮区域
        button_layout = QHBoxLayout()
        
        self.search_button = QPushButton("搜索")
        self.search_button.setDefault(True)
        self.search_button.clicked.connect(self.perform_search)
        button_layout.addWidget(self.search_button)
        
        self.clear_button = QPushButton("清除条件")
        self.clear_button.clicked.connect(self.clear_conditions)
        button_layout.addWidget(self.clear_button)
        
        button_layout.addStretch()
        
        self.cancel_button = QPushButton("取消")
        self.cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_button)
        
        layout.addLayout(button_layout)
    
    def toggle_age_search(self, enabled: bool):
        """切换年龄搜索启用状态"""
        self.age_min_spin.setEnabled(enabled)
        self.age_max_spin.setEnabled(enabled)
    
    def toggle_time_search(self, enabled: bool):
        """切换时间搜索启用状态"""
        self.start_date_edit.setEnabled(enabled)
        self.start_time_edit.setEnabled(enabled)
        self.end_date_edit.setEnabled(enabled)
        self.end_time_edit.setEnabled(enabled)
    
    def set_quick_time(self, time_type: str):
        """设置快速时间选择"""
        current_date = QDate.currentDate()
        current_time = QTime.currentTime()
        
        if time_type == "today":
            start_date = current_date
            start_time = QTime(0, 0, 0)
            end_date = current_date
            end_time = QTime(23, 59, 59)
        elif time_type == "yesterday":
            start_date = current_date.addDays(-1)
            start_time = QTime(0, 0, 0)
            end_date = current_date.addDays(-1)
            end_time = QTime(23, 59, 59)
        elif time_type == "week":
            start_date = current_date.addDays(-7)
            start_time = QTime(0, 0, 0)
            end_date = current_date
            end_time = QTime(23, 59, 59)
        elif time_type == "month":
            start_date = current_date.addDays(-30)
            start_time = QTime(0, 0, 0)
            end_date = current_date
            end_time = QTime(23, 59, 59)
        else:
            return
        
        self.time_enable_check.setChecked(True)
        self.start_date_edit.setDate(start_date)
        self.start_time_edit.setTime(start_time)
        self.end_date_edit.setDate(end_date)
        self.end_time_edit.setTime(end_time)
    
    def clear_time_search(self):
        """清除时间搜索条件"""
        self.time_enable_check.setChecked(False)
    
    def clear_conditions(self):
        """清除所有搜索条件"""
        # 基本信息
        self.sample_number_edit.clear()
        self.patient_name_edit.clear()
        self.gender_combo.setCurrentText("全部")
        
        # 年龄搜索
        self.age_enable_check.setChecked(False)
        self.age_min_spin.setValue(0)
        self.age_max_spin.setValue(150)
        
        # 时间搜索
        self.time_enable_check.setChecked(False)
        self.start_date_edit.setDate(QDate.currentDate().addDays(-7))
        self.start_time_edit.setTime(QTime(0, 0, 0))
        self.end_date_edit.setDate(QDate.currentDate())
        self.end_time_edit.setTime(QTime(23, 59, 59))
        
        # 仪器信息
        self.instrument_model_edit.clear()
        self.instrument_id_edit.clear()
        self.analysis_mode_edit.clear()
        self.protocol_edit.clear()
        
        # 状态
        self.status_combo.setCurrentText("全部")
    
    def collect_search_conditions(self) -> Dict[str, Any]:
        """收集搜索条件"""
        conditions = {}
        
        # 基本信息搜索
        sample_number = self.sample_number_edit.text().strip()
        if sample_number:
            conditions['sample_number'] = sample_number
        
        patient_name = self.patient_name_edit.text().strip()
        if patient_name:
            conditions['patient_name'] = patient_name
        
        gender = self.gender_combo.currentText()
        if gender != "全部":
            conditions['patient_gender'] = gender
        
        # 年龄区间搜索
        if self.age_enable_check.isChecked():
            age_min = self.age_min_spin.value()
            age_max = self.age_max_spin.value()
            if age_min > 0 or age_max < 150:
                conditions['age_range'] = (age_min, age_max)
        
        # 时间区间搜索
        if self.time_enable_check.isChecked():
            start_datetime = datetime.combine(
                self.start_date_edit.date().toPyDate(),
                self.start_time_edit.time().toPyTime()
            )
            end_datetime = datetime.combine(
                self.end_date_edit.date().toPyDate(),
                self.end_time_edit.time().toPyTime()
            )
            conditions['time_range'] = (start_datetime, end_datetime)
        
        # 仪器信息搜索
        instrument_model = self.instrument_model_edit.text().strip()
        if instrument_model:
            conditions['machine_model'] = instrument_model
        
        instrument_id = self.instrument_id_edit.text().strip()
        if instrument_id:
            conditions['machine_id'] = instrument_id
        
        analysis_mode = self.analysis_mode_edit.text().strip()
        if analysis_mode:
            conditions['analysis_mode'] = analysis_mode
        
        protocol = self.protocol_edit.text().strip()
        if protocol:
            conditions['protocol'] = protocol
        
        # 状态搜索
        status = self.status_combo.currentText()
        if status != "全部":
            conditions['status'] = status
        
        return conditions
    
    def perform_search(self):
        """执行搜索"""
        try:
            conditions = self.collect_search_conditions()
            
            if not conditions:
                QMessageBox.warning(self, "警告", "请至少输入一个搜索条件")
                return
            
            # 发送搜索信号
            self.search_requested.emit(conditions)
            
            # 关闭对话框
            self.accept()
            
        except Exception as e:
            logger.error(f"执行搜索失败: {e}")
            QMessageBox.critical(self, "错误", f"搜索失败: {e}")
    
    def get_search_conditions(self) -> Dict[str, Any]:
        """获取搜索条件（供外部调用）"""
        return self.collect_search_conditions()
